﻿using Consul;
using M.Core.RmoteCall.Log;
using M.Core.RmoteCall.RpcCall.Pool;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static M.Core.ClientEventMgr;

namespace M.Core.RmoteCall.RpcCall
{
    /// <summary>
    /// 处理调用Rpc方法时发生错误时的相关处理
    /// </summary>
    public class RpcEventMgr
    {
        public static RpcEventMgr _consulEventMgr = new RpcEventMgr();
        private RpcEventMgr() { }
        public static RpcEventMgr GetInstance()
        {
            return _consulEventMgr;
        }
        internal Task SendErrorEvent(ChangeType changeType, RpcPoolItem callSocketObject, Exception ex)
        {
            return Task.Run(() =>
            {
                CallLog.GetInstance().Logger(ex, $"调用Rpc发生错误 Type:{changeType}");

                var callSocket = callSocketObject.GetInnerObject();
                if (callSocketObject == null|| callSocketObject.GetInnerObject()==null) return;
                

                var name = callSocket.callModel.Name;
                var iPEndPoint = callSocket.callModel.iPEndPoint;
                switch (changeType)
                {
                    case ChangeType.Add:
                        break;
                    case ChangeType.Remove:
                        break;
                    case ChangeType.ReBulidModel:
                        CatalogService[] oldResponse = ServiceDiscovery.GetInstance().Get(callSocket.callModel.Name);
                        var first = oldResponse.FirstOrDefault(i => i.ServiceAddress.Equals(iPEndPoint.Address.ToString()) && i.ServiceMeta["ThriftPort"].Equals(iPEndPoint.Port.ToString()));
                        if (first != null)
                        {
                            ClientEventMgr.GetInstance().SendEvent(ChangeType.ReBulidModel, first);
                        }
                        break;
                    default:
                    case ChangeType.Reconn:
                        callSocket.SocketReset();
                        break;
                }
                if (callSocketObject.IsUsing)
                {
                    callSocketObject.Dispose();
                }
            });
        }
    }
}
